'''
长生爱康保重大疾病保险
'''
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests,re
from common.helper import Helper
from urllib.parse import urlencode


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "长生爱康保重大疾病保险"

    # 生产产品数据
    def genProductInfo(self):

        plan = {

            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 41)],
                # 性别
                "gender": ["M", "F"],
                # 缴费期间
                "interval": ["5", "10", "15", "20"],
                # 保险金额
                "money": ["50000", "100000", "150000", "200000", "250000", "300000"],
                # 保障期限
                "expire": ["终身"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 缴费期间
                "interval": ["5", "10", "15", "20"],
                # 保险金额
                "money": ["50000", "100000", "150000", "200000"],
                # 保障期限
                "expire": ["终身"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(46, 51)],
                # 性别
                "gender": ["M", "F"],
                # 缴费期间
                "interval": ["5", "10"],
                # 保险金额
                "money": ["50000", "800000"],
                # 保障期限
                "expire": ["终身"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(46, 51)],
                # 性别
                "gender": ["M", "F"],
                # 缴费期间
                "interval": ["5", "10"],
                # 保险金额
                "money": ["50000", "800000"],
                # 保障期限
                "expire": ["终身"]
            },
            "planE": {
                # 年龄段
                "year": [str(i) for i in range(51, 56)],
                # 性别
                "gender": ["M", "F"],
                # 缴费期间
                "interval": ["5"],
                # 保险金额
                "money": ["50000"],
                # 保障期限
                "expire": ["终身"]
            }

        }

        for k in plan:

            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["interval"], plan[k]["money"],
                             plan[k]["expire"]):
                # 写入数据库
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4]))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4]))

    # 执行爬虫
    def requestJson(self, dt=None):

        data = {

            "prem_callback": "jsonp1578892173730",
            "00000000000000001469_TextAge": ""+dt["year"]+"Y",
            "00000000000000001470_Sex": dt["gender"],
            "00000000000000001472_FeeYear": ""+dt["interval"]+"Y",
            "00000000000000001473_Period": "1000Y",
            "00000000000000001474_Amnt": dt["money"],
            "RiskCode": "00199006"

        }

        payload = urlencode( data )

        r = requests.get( url=domain[self.name]["url"] + payload,headers=domain[self.name]["header"])

        status = re.search(r'"status":"(.*?)"',r.text).groups(1)[0]

        if r.status_code == 200 and status == "1":

            price = Helper.decimalParse(re.search(r'productPrem":"(.*?)"',r.text).groups(1)[0])

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            print("流程不正确更新价格失败:",dt["id"])
            self.mysql.updateTask(data)

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.requestJson(dt=dt)
